package com.ruoyi.web.controller.common;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.file.core.FileProperties;
import com.ruoyi.common.file.core.FileTemplate;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.MimeTypeUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * 通用请求处理
 *
 * @author ruoyi
 */
@RestController
public class CommonController {
    @Resource
    private FileTemplate fileTemplate;
    @Resource
    private FileProperties fileProperties;

    /**
     * 通用上传请求
     */
    @PostMapping("/common/upload")
    public AjaxResult uploadFile(MultipartFile file) {
        try {
            // 校验文件类型和大小
            FileUploadUtils.assertAllowed(file, MimeTypeUtils.IMAGE_EXTENSION);

            String fileName = file.getOriginalFilename();
            fileTemplate.putObject(fileProperties.getBucketName(), file.getOriginalFilename(), file.getInputStream());

            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName", fileName);
            ajax.put("url", fileProperties.getBaseUrl() + fileName);
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

}
